﻿using System;
using System.Xml;
using System.Windows.Forms;
using SdmxMl.GenericMetadata;
using SdmxMl.Manager;
using SdmxMl.Common;
using SdmxMl.Structure;
using PluginInterface;

namespace SilcQuest
{
    /// <summary> Dialog for Multi load of questionnaires (RE 3.1) </summary>
    public partial class DlgLoadQuest : Form
    {
        #region Private members

        private SmManager smCati;
        private PluginEvent PluginEventExposed;
        private const string dateFormat = "yyyy-MM-dd";

        #endregion

        #region Constructor

        public DlgLoadQuest(SmManager sm, PluginEvent PlugEventExposed)
        {
            InitializeComponent();
            smCati = sm;
            PluginEventExposed = PlugEventExposed;
            if (smCati == null)
                smCati = ReferenceManager.GetSmContainerImage();

            ucDatePickerFrom.Date = DateTime.Now.ToString(dateFormat);
            ucDatePickerTo.Date = DateTime.Now.ToString(dateFormat);
            checkedListBox.SelectedIndex = 0;
        }
        #endregion

        #region Load event

        private void buttonLoad_Click(object sender, EventArgs e)
        {
            // If date cleared force max limits
            if (ucDatePickerFrom.Date == string.Empty)
                ucDatePickerFrom.Date = DateTime.Now.ToString(dateFormat);
            if (ucDatePickerTo.Date == string.Empty)
                ucDatePickerTo.Date = DateTime.Now.ToString(dateFormat);

            // if from > to set to same as from
            DateTime dtFrom = Convert.ToDateTime(ucDatePickerFrom.Date);
            DateTime dtTo = Convert.ToDateTime(ucDatePickerTo.Date);
            if (dtFrom > dtTo)
            {
                dtTo = dtFrom;
                ucDatePickerTo.Date = dtTo.ToString(dateFormat);
            }


            if (checkedListBox.CheckedItems.Count == 0)
            {
                MessageBox.Show("No domain selected!", "Caution", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {
                MetadataSetType metaSet;
                MetadataStructureDefinitionType msd = null; 

                SmManager sm = new SmManager();

                SilcGroupInfo silcGroup = new SilcGroupInfo();
                foreach (string questType in checkedListBox.CheckedItems)
                {
                    bool isTechnical = questType.StartsWith(SilcGroupInfo.TECH_MARKER);
                    string id = isTechnical ? silcGroup.GmdStarter + questType : silcGroup.PrependMsId(questType);
                    // For each year in selected rance
                    for (int y = dtFrom.Year; y <= dtTo.Year; ++y)
                    {
                        ArtefactRefBase arb = new ArtefactRefBase(id, silcGroup.AgencyId, y.ToString() + ".0");
                        metaSet = smCati.GetArtefact(SdmxArtefactType.MetadataSet, arb, false) as MetadataSetType;
                        if (metaSet == null)
                        {
                            metaSet = sm.GetArtefact(SdmxArtefactType.MetadataSet, arb, true) as MetadataSetType;
                        }
                        else
                        {
                            sm.PutArtefact(SdmxArtefactType.MetadataSet, metaSet);
                        }

                        if (metaSet == null)
                            throw new ApplicationException("Unable to locate metadata for quest: " + arb.FullIdent);

                        // Refresh main tree get XML image
                        XmlDocument xDoc = sm.GetMetasetAsDocument(metaSet.FullIdent);
                        //Raise update event for main program (if already exists, will not be updated)
                        if (PluginEventExposed != null)
                            PluginEventExposed(this, new PluginEventArgs(xDoc));
                        sm = new SmManager();

                        if (msd == null)
                        {
                            sm = new SmManager();
                            msd = sm.GetArtefact(SdmxArtefactType.MetadataStructureDefinitions, metaSet.MetadataStructureRef, true) as MetadataStructureDefinitionType;
                            // Get also dependencies
                            sm.LoadMissingArtefactsFromRegistry(msd.ArtefactRefList);

                            // get XML image
                            xDoc = sm.GetAsDocument();
                            //Raise update event for main program
                            if (PluginEventExposed != null)
                                PluginEventExposed(this, new PluginEventArgs(xDoc));
                        }
                    }
                }
                this.Close();
            }
        }
        #endregion

        #region Select / unselect All

        private void checkBoxSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            // if all selected, clear if not select all
            bool allChecked = checkedListBox.CheckedItems.Count == checkedListBox.Items.Count;
            for (int i = 0; i < checkedListBox.Items.Count; ++i)
                checkedListBox.SetItemChecked(i, allChecked ? false : true);
        }
        #endregion

    }
}
